package com.htfyun;

import android.app.Activity;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;

import com.htfyun.utils.DebugLog;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;

import group.pals.android.lib.ui.filechooser.utils.E;

/**
 * Created by sst on 2017/11/27.
 */

public enum ScanMyBooksDirManager {
    INSTANCE;


    public List<File> getFiles() {

        return getBookFilesByDirection(new File(Constants.getMyBooksPath()));
        
    }

    private static final String SUFFIX_TXT = "txt";
    private static final String SUFFIX_PDF = "pdf";
    private static final String SUFFIX_EPUB = "epub";

    private List<File> getBookFilesByDirection(File file) {
        List<File> bookFiles = new ArrayList<>();

        List<String> supportedSuffix = new ArrayList<>();
        supportedSuffix.add(SUFFIX_TXT);
        supportedSuffix.add(SUFFIX_PDF);
        supportedSuffix.add(SUFFIX_EPUB);
        
        try {

            if (file.isDirectory()) {
                File[] fileList = file.listFiles();
                for (File f : fileList) {
                    if (f.isFile()) {

                        String bookName = f.getName();
                        final int index = bookName.lastIndexOf('.');

                        String myExtension = (index > 0) ? bookName.substring(index + 1).toLowerCase().intern() : "";

                        if (supportedSuffix.contains(myExtension)) {
                            bookFiles.add(f);
                        }
                    } else if (f.isDirectory()) {
                        bookFiles.addAll(getBookFilesByDirection(f));
                    }
                }
            }

        } catch (Exception e) {
        }
        
        Collections.sort(bookFiles, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                return (int)(o1.lastModified() - o2.lastModified());
            }
        });

        return bookFiles;
    }
    
    
    
   

}
